//
//  JHExplainInfoView.m
//  JuniRengLish_iOS
//
//  Created by Maiyou on 2019/5/23.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHExplainInfoView.h"
#import <AVFoundation/AVFoundation.h>
#import "JHExplainDetailViewController.h"
#import "JHSearchWordViewController.h"

@implementation JHExplainInfoView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self = [[NSBundle mainBundle] loadNibNamed:@"JHExplainInfoView" owner:self options:nil].firstObject;
        self.frame = frame;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        tap.cancelsTouchesInView = NO;
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
        self.backView.y = JKScreenH;
        
        
        [self.closeButton layoutButtonWithImageStyle:ZJButtonImageStyleLeft imageTitleToSpace:8];
        [self.explainDetail layoutButtonWithImageStyle:ZJButtonImageStyleLeft imageTitleToSpace:8];
        [self.searchWord layoutButtonWithImageStyle:ZJButtonImageStyleLeft imageTitleToSpace:8];
        [self.addNewWord layoutButtonWithImageStyle:ZJButtonImageStyleLeft imageTitleToSpace:8];
    }
    return self;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([touch.view isDescendantOfView:self.backView]) {
        return NO;
    }
    return YES;
}

- (void)tapClick:(UITapGestureRecognizer *)tap
{
    [self hiddenView];
}

- (FSAudioStream *)audioStream
{
    if (!_audioStream)
    {
        //创建FSAudioStream对象
        _audioStream = [[FSAudioStream alloc]init];
        _audioStream.onFailure = ^(FSAudioStreamError error,NSString *description){
            NSLog(@"播放过程中发生错误，错误信息：%@",description);
        };
        _audioStream.onCompletion = ^(){
            NSLog(@"播放完成!");
        };
        _audioStream.onStateChange = ^(FSAudioStreamState state) {
            
        };
        [_audioStream setVolume:1];//设置声音
    }
    return _audioStream;
}

- (void)setDataDic:(NSDictionary *)dataDic
{
    _dataDic = dataDic;
    
    self.showWord.text = dataDic[@"rq"];
    
    self.showBritish.text = [NSString stringWithFormat:@"英[%@]", dataDic[@"uksm"]];
    
    self.showAmerican.text = [NSString stringWithFormat:@"美[%@]", dataDic[@"ussm"]];
    
    NSString * explain = @"";
    NSArray * array = dataDic[@"basic"];
    for (int i = 0; i < [array count]; i ++)
    {
        [explain isEqualToString:@""] ? explain = array[i] : (explain = [NSString stringWithFormat:@"%@\n%@", explain, array[i]]);
    }
    self.showExplain.text = explain;
    
    NSArray * recArray = dataDic[@"rec"];
    // 下划线
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    if (recArray.count > 1)
    {
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:recArray[0] attributes:attribtDic];
        [attribtStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[recArray[0] length])];
        [self.explainButton1 setAttributedTitle:attribtStr forState:0];
        
        NSMutableAttributedString *attribtStr1 = [[NSMutableAttributedString alloc]initWithString:recArray[1] attributes:attribtDic];
        [attribtStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[recArray[1] length])];
        [self.explainButton2 setAttributedTitle:attribtStr1 forState:0];
    }
    else if (recArray.count > 0)
    {
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:recArray[0] attributes:attribtDic];
        [attribtStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[recArray[0] length])];
        [self.explainButton1 setAttributedTitle:attribtStr forState:0];
        self.explainButton2.hidden = YES;
    }
    else
    {
        self.explainButton1.hidden = YES;
        self.explainButton2.hidden = YES;
    }
    
    [self showView];
}

- (void)showView
{
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.backView.y = JKScreenH - kTabbarSafeBottomMargin - 250;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hiddenView
{
    [UIView animateWithDuration:0.3 animations:^{
        self.backView.y = JKScreenH;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

- (IBAction)buttonClick:(id)sender
{
    UIButton * button = sender;
    switch (button.tag) {
        case 10:
            
            break;
        case 20://英式发音
            [self playWord:self.showWord.text Lan:@"uk"];
            break;
        case 30://美式发音
            [self playWord:self.showWord.text Lan:@"en"];
            break;
        case 40:
        {
            [self hiddenView];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                JHExplainDetailViewController * detail = [JHExplainDetailViewController new];
                detail.explainWord = self.showWord.text;
                detail.wordDic = self.dataDic;
                detail.type = 2;
                [self.currentVC.navigationController pushViewController:detail animated:YES];
            });
        }
            break;
        case 50:
        {
            [self hiddenView];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                JHSearchWordViewController * detail = [JHSearchWordViewController new];
                detail.word = self.showWord.text;
                [self.currentVC.navigationController pushViewController:detail animated:YES];
            });
        }
            break;
        case 60://关闭
            [self hiddenView];
            break;
            
        default:
            break;
    }
}

- (IBAction)explainButtonClick:(id)sender
{
    [self hiddenView];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIButton * button = sender;
        [self getTranferWordInfo:[button.titleLabel.attributedText string]];
    });
}

- (void)getTranferWordInfo:(NSString *)word
{
    [DJHttpTool postWithURL:@"http://dict.youdao.com/jsonresult" params:@{@"q":word, @"pos":@"yidu", @"type":@"1"} success:^(id json) {
        self.dataDic = json;
    } failure:^(NSError *error) {
        
    }];
}

- (void)playWord:(NSString *)word Lan:(NSString *)lan
{
    word = [word stringByAddingPercentEncodingWithAllowedCharacters:  [NSCharacterSet URLUserAllowedCharacterSet]];
    NSString * urlStr = [NSString stringWithFormat:@"https://fanyi.baidu.com/gettts?lan=%@&text=%@&spd=2&source=web", lan, word];
    self.audioStream.url = [NSURL URLWithString:urlStr];
    [self.audioStream play];
}


@end
